package Client; //done

import java.io.IOException;

import ocsf.client.AbstractClient;

/**
 * This class controls the message from/to server
 * @author waleed
 */
public class CCRM_Client_Controller extends AbstractClient{
	
	/** The received message from server */
	private Object messagefromserver = null;
	
	/** Flag that shows if client can read message from server */
	private boolean canRead = false;
	
	/** Flag that shows if client can send message to server */
	private boolean canSend = true;
	
	/**
	* Constructs an instance of the chat client.
	*
	* @param localhost The server to connect to.
	* @param 5555 The port number to connect on.
	*/
	public CCRM_Client_Controller(){
		super("localhost", 5555);
	}	
	
	/**
	 * @param host
	 * @param port
	 */
	public CCRM_Client_Controller(String host, int port) throws IOException{
		super(host, port);
		openConnection();
	}

	
	/**
	 * @return the messagefromserver
	 */
	public synchronized Object getMessagefromserver(){
		canSend = true;
		return messagefromserver;		
	}
		
	/**
	 * This function checks if the client can read data from server
	 * @return canRead
	 */
	public synchronized boolean checkIfClientCanRead(){
		return canRead;
	}

	/**
	 * This function handles the message from the server
	 */
	protected synchronized void handleMessageFromServer(Object msg){
		try{
			if (msg.getClass() == String.class){
				if (((String)(msg)).equals("CHECK")){
					System.out.println("CHECK");
						return;
				}
			}
			this.messagefromserver = msg;
			canRead = true;
		}
		catch(Exception e){
			messagefromserver = null;
		};		
	}
	
	/**
	* This function handles all data coming from the UI            
	*
	* @param message The message from the UI. 
	* @throws IOException Signals that an I/O exception has occurred.   
	*/ 
	public synchronized void handleMessageFromClientUI(String[] message){
		  if (!canSend)
			  return;
		  try{
			  	sendToServer(message);	
			  	canRead = false;
			  	canSend = false;
		  }
		  catch(IOException e){
			  System.out.println("Could not send message to server.  Terminating client.");
			  quit();
		  }
	  } 
	  	  
	  /**
	   * This function terminates the client.
	   */
	  public void quit(){
		try{
			 closeConnection();		     
	    }
	    catch(IOException e){}	    
	    //System.exit(0);
	  }    	
}


